<template>
  <div>
    <van-form @submit="onSubmit" @failed="onFailed">
      <van-field
        v-model="listQuery.strMaterialname"
        :rules="[{ pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,15}$/ ,message: '请输入正确内容' }]"
        label="素材名称"
        name="strMaterialname"
        placeholder="请输入"
      />
      <van-field
        readonly
        clickable
        name="iType"
        label="素材类型"
        :value="iType"
        placeholder="选择素材类型"
        @click="showPicker1('素材类型', 4, 'iType')"
        :rules="[{ required: true, message: '请选择素材类型' }]"
      />
      <van-field
        readonly
        clickable
        name="strMaterialdetail"
        label="素材标签"
        :value="strMaterialdetail"
        placeholder="选择素材标签"
        @click="showPicker1('素材标签', 3, 'strMaterialdetail')"
        :rules="[{ required: true, message: '请选择素材标签' }]"
      />
      <van-field
        readonly
        clickable
        name="iDevtype"
        label="设备类型"
        :value="iDevtype"
        placeholder="选择设备类型"
        @click="showPicker1('设备类型', 7, 'iDevtype')"
        :rules="[{ required: true, message: '请选择设备类型' }]"
      />

      <van-field readonly name="iOrgsysnum" label="所属机构" :value="iOrgsysnum" placeholder="选择所属机构" />
      <van-field
        v-if="listQuery.iType == 1"
        name="strDownload"
        label="图片上传"
        :rules="[{ required: true, message: '请上传图片' }]"
      >
        <van-uploader
          slot="input"
          v-model="fileList"
          @oversize="onOversize"
          :after-read="afterRead"
          :max-count="1"
        />
      </van-field>
      <van-field
        v-else
        v-model="listQuery.strDownload"
        :rules="[{ validator ,message: '请输入正确内容' }]"
        label="素材地址"
        name="strDownload"
        placeholder="请输入"
      />
      <div style="margin: 16px;">
        <van-button block class="vant-btn-dark" :disabled="isDisable" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  getOpts,
  fetchlist,
  // fetchOrglist,
  addPieceData,
  modifieData
} from '../../api/material'
import axios from 'axios'

export default {
  name: 'addMaterial',
  data() {
    return {
      fileList: [], //  [{ url: 'https://img.yzcdn.cn/vant/leaf.jpg' }],
      value: 2016,
      listQuery: {
        iType: '',
        strMaterialdetail: '',
        iDevtype: '',
        strMaterialname: '',
        iOrgsysnum: '180000021',
        strOperator: 'Super Admin',
        strDownload: ''
      },
      showPicker: false,
      iType: '',
      strMaterialdetail: '',
      iDevtype: '',
      options: {},
      cashObj: {},
      isDisable: false
    }
  },
  watch: {
    'listQuery.strDownload': {
      handler(newVal) {
        const img = new Image()
        img.src = newVal
        img.onload = () => {
          if (img.complete) {
            this.listQuery.strResolution = img.width + '*' + img.height
          }
        }
      },
      immediate: true
    }
  },
  created() {
    // fetchOrglist().then(res => {
    //   this.columns = []
    //   this.columns = this.combination(res.data)
    // })
    this.getTypesys()

    this.iOrgsysnum = '江苏农商银行'

    // 路由存在参数————修改 反之————添加
    if (this.$route.query.row) {
    console.log(JSON.parse(this.$route.query.row))
      const routeParams = JSON.parse(this.$route.query.row)
      this.listQuery = {
        iType: routeParams.iType,
        strMaterialdetail: routeParams.strMaterialdetail,
        iDevtype: routeParams.iDevtype,
        strMaterialname: routeParams.strMaterialname,
        iOrgsysnum: routeParams.iOrgsysnum,
        strOperator: routeParams.strOperator,
        strDownload: routeParams.strDownload,
        strResolution: routeParams.strResolution,
        id: routeParams.id
      }
      this.fileList.push({url:routeParams.strDownload})
      this.iType = routeParams.iTypename
      this.strMaterialdetail = routeParams.strMaterialdetail
      // this.$nextTick(()=>{
      //   console.log(this.options, 'options')
      //   this.options[3].map(item=>{
      //     if (routeParams.strMaterialdetail === item.strCode) {
      //       this.strMaterialdetail = item.strValue
      //     }
      //   })
      // })
      this.iDevtype = routeParams.iDevtypename
    }
  },
  methods: {
    onSubmit(values) {
      let newObj = Object.assign(values, this.listQuery)
      delete newObj.uploader
      this.isDisable = true
      if (!this.$route.query.row) {
        addPieceData(newObj).then(() => {
          this.$toast({
            type: 'success',
            message: '添加成功',
            duration: '1000',
            onClose: () => {
              this.$router.push({ path: 'list' })
              this.isDisable = false
            }
          })
        })
      } else {
        modifieData(newObj).then(() => {
          this.$toast({
            type: 'success',
            message: '修改成功',
            duration: '1000',
            onClose: () => {
              this.$router.push({ path: 'list' })
              this.isDisable = false
            }
          })
        })
      }
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
      return reg.test(val)
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo)
    },
    showPicker1(title, ity, name) {
      const column = this.options[ity + '']
      if (!this.picker) {
        this.picker = this.$createPicker({
          title,
          data: [column],
          alias: {
            value: 'strCode',
            text: 'strValue'
          },
          // data: this.column,
          onSelect: (selectedVal, selectedIndex, selectedText) =>
            this.selectHandle(selectedVal, selectedIndex, selectedText, name),
          onCancel: this.cancelHandle
        })
      }
      this.picker.show()
    },
    selectHandle(selectedVal, selectedIndex, selectedText, name) {
      this.listQuery[name] = selectedVal[0]
      this[name] = selectedText[0]
      this.picker = null
    },
    cancelHandle() {
      this.picker = null
    },

    combination(oldlist) {
      let arr = []
      oldlist.map(item => {
        let newObj = {
          text: item.strOrgname,
          value: item.strOrgnum
        }
        if (item.yhlist) {
          const children = this.combination(item.yhlist)
          newObj = { ...newObj, children: children }
        }
        arr.push(newObj)
      })
      return arr
    },
    getTypesys() {
      getOpts({ typeInfo: [3, 4, 7] }).then(res => {
        //  3 素材标签 4 素材类型 7 设备类型
        this.options = res.data
      })
    },
    getList() {
      let param = {
        iOrgnum: '180000021',
        pagenum: 1
      }

      fetchlist(param)
        .then(res => {
          this.listData = res.data
        })
        .catch(err => console.log(err))
    },
    afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'

      // 此时可以自行将文件上传至服务器
      let content = file.file
      let data = new FormData()
      data.append('uploadFile', content)

      axios
        .post('http://192.168.241.200:8888/system/fileRequest', data)
        .then(res => {
          // let datas = res.data.datas.path;
          if (res.data.result.transCode === 'success') {
            this.listQuery.strDownload = res.data.result.result.replace(
              '/home/topsales/static',
              'http://192.168.241.200:8888'
            )
            file.status = 'success'
          } else {
            setTimeout(() => {
              file.status = 'failed'
              file.message = '上传失败'
            }, 1000)
          }
        })
    },
    onOversize(file) {
      console.log(file)
    }
  }
}
</script>

<style lang="scss" scoped>
.uploadImg {
  display: flex;
  padding: 16px;
  align-items: center;
  align-self: start;
  justify-content: space-around;
  span {
    font-size: 13px;
  }
  .right-soan {
    flex: 2;
    text-align: left;
  }
}
.van-uploader__wrapper {
  flex-wrap: nowrap;
}
</style>
